<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .layui-table-cell{
            text-align:center;
            height: auto;
            white-space: normal;
        }
        .layui-upload-img {
            width: 80px;
            height: 80px;
            margin: 5px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品名称</label>
                            <div class="layui-input-inline">
                                <input id="input1" type="text" name="name" autocomplete="off" class="layui-input" value="">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">商品状态</label>
                            <div class="layui-input-inline">
                                <select id="select1" name="status" lay-verify="">
                                    <option value="0">未上架</option>
                                    <option value="1">已上架</option>
                                    <option value="" selected>全部</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button id="searchBtn" type="button" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add">添加</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="up">上架</button>
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="down">下架</button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="uppers">上传多附件</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>

        </script>
    </div>
</div>
<script id="uppersTemplate" type="text/html">
    <div class="layui-form-item">
        <label class="layui-form-label">商品图片</label>
        <div class="layui-input-inline">
            <div class="layui-upload">
                <button type="button" class="layui-btn" id="test2">多图片上传</button>
                <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px; width: 360px">
                    预览图：
                    <div class="layui-upload-list" id="demo2" style="width: 400px"></div>
                </blockquote>
                <input id="ids" type="hidden" name="ids">
            </div>
        </div>
    </div>
</script>
<script id="productTemplate" type="text/html">
    <form class="layui-form" lay-filter="categoryForm">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">一级分类</label>
                <div class="layui-input-inline">
                    <select id="firstSelect" lay-filter="topCategory"></select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">二级分类</label>
                <div class="layui-input-inline">
                    <select id="secondSelect" lay-filter="lastCategory" ></select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">三级分类</label>
                <div class="layui-input-inline">
                    <select id="thirdSelect" name="categoryId"></select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">商品名称</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id"/>
                    <input  type="text" name="name" autocomplete="off" placeholder="请输入商品名称" class="layui-input">
                </div>
            </div>

        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">商品标题</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id"/>
                    <input type="text" name="title" autocomplete="off" placeholder="请输入描述" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">商品价格</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id"/>
                    <input type="text" name="price" autocomplete="off" placeholder="请输入价格" class="layui-input">
                </div>
            </div>

        </div>
        <div class="layui-form-item"  >
            <div class="layui-inline" style="margin: -130px 0px 0px 0px">
                <label class="layui-form-label">商品特色</label>
                <div class="layui-input-inline">
                    <input type="hidden" name="id"/>
                    <input type="text" name="feature" autocomplete="off" placeholder="请输入价格" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
            <label class="layui-form-label">商品首页图</label>
            <div class="layui-upload">
                <button type="button" class="layui-btn" id="test1">上传附件</button>
                <div style="margin: 10px 10px 10px 110px" class="layui-upload-list">
                    <img width="95px" height="95px" class="layui-upload-img" id="demo1">
                    <p id="demoText"></p>
                </div>
                <div style="width: 95px; margin: 10px 10px 10px 110px;" >
                    <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                        <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                </div>
                <input type="hidden" id="aaaa" name="homeImg" autocomplete="off" placeholder="" class="layui-input">
            </div>
            </div>


        </div>
        <div class="layui-form-item"  style="margin: 10px 10px 10px 180px">
            <div class="layui-input-block" >
                <button id="saveBtn" type="button" class="layui-btn" >立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js"></script>
<script th:inline="none" type="text/javascript">
    layui.use(["table", "layer", "laydate", "form","upload","common","element"], function () {
        var table = layui.table;
        var $ = layui.jquery;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var form = layui.form;
        var upload=layui.upload;
        var element=layui.element;

        $("#searchBtn").on("click", function () {
            table.render({
                elem: '#currentTableId',
                url: '/product/list',
                toolbar: '#toolbarDemo',
                where: {keyword: $("#input1").val(),status:encodeURIComponent($("#select1").val())},
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                cols: [[
                    {type: "checkbox", width: 50},
                    {field: 'id',  title: '商品ID', sort: true},
                    {field: 'categoryId',  title: '商品分类ID', sort: true},
                    {field: 'name',  title: '商品名称'},
                    {field: 'price', title: '价钱', sort: true},
                    {field: 'status', title: '状态', sort: true},
                    { title: "主页图", field: "homeImg",
                        templet:function (d) {
                            if (d.homeImg!==''){
                                return '<img src="'+d.homeImg+'" style="height: 50px;width: 50px"/>'
                            }else {
                                return ''
                            }
                        },
                        align: "center"
                    },
                    {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 15,
                page: true,
                skin: 'line'
            });
        });
        $("#searchBtn").click();



        $("body").on("click", "#saveBtn", function () {
            $.post("/product/save", form.val("categoryForm"), function () {
                layer.closeAll();
                $("#searchBtn").click();
            });
        });
        $("body").on("click", "#saveBtn01", function () {

                $("#searchBtn").click();
        });

        function renderUpload() {
            var uploadInst = upload.render({
                elem: '#test1'
                ,url: '/product/avatar' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                    element.progress('demo', '0%'); //进度条复位
                    layer.msg('上传中', {icon: 16, time: 0});
                }
                ,done: function(res){
                    //如果上传失败
                    if(res.code > 0){
                        return layer.msg('上传失败');
                    }
                    //上传成功的一些操作

                    $("#aaaa").val(res.data.avatar);

                    //……
                    $('#demoText').html(''); //置空上传失败的状态
                }
                ,error: function(){
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function(){
                        uploadInst.upload();
                    });
                }
                //进度条
                ,progress: function(n, elem, e){
                    element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                    if(n == 100){
                        layer.msg('上传完毕', {icon: 1});
                    }
                }
            });
        }

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            console.log(obj);
            if (obj.event === 'add') {  // 监听添加操作
                $.get("/category/child",{id:0},function (categories) {
                    layer.open({
                        type: 1,
                        area: ["700px", "500px"],
                        title: "新增商品",
                        content: $("#productTemplate").html()
                    });

                    $.each(categories,function (i,v) {
                            /*$.get("/category/child",{id:v.id},function (categories01) {
                                $.each(categories01,function (i,v02) {
                                    $("#thirdSelect").append('<option value="'+v02.id+'">'+v02.name+'</option>')
                                })
                            })*/
                        $("#firstSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                    })
                    renderUpload();
                    form.render();
                })
            }else if (obj.event === 'up') {
                var checkStatus = table.checkStatus('currentTableId')
                    ,data = checkStatus.data;
                var ids=[];
                $.each(data,function(i,v) {
                    ids[i]=v.id;
                });
                console.log(ids);
                $.post("/product/doUp", {ids:ids}, function () {
                    layer.closeAll();
                    $("#searchBtn").click();
                });
            }else if (obj.event === 'down') {
                var checkStatus = table.checkStatus('currentTableId')
                    ,data = checkStatus.data;
                var ids=[];
                $.each(data,function(i,v) {
                    ids[i]=v.id;
                });
                console.log(ids);
                $.post("/product/doDown", {ids:ids}, function () {
                    layer.closeAll();
                    $("#searchBtn").click();
                });
            }
            });
        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;

            if (obj.event === 'edit') {
                $.get("/product/"+data.id,function (m) {
                        layer.open({
                            type:1,
                            area:['700px','500px'],
                            title:"编辑商品",
                            content:$("#productTemplate").html()
                        });
                        $.each(m.list1,function (i,v) {
                            $("#firstSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                        });
                        $("#firstSelect").val(m.topCategory);
                        $.each(m.list2,function (i,v) {
                            $("#secondSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                        });
                        $("#secondSelect").val(m.lastCategory);
                        $.each(m.list3,function (i,v) {
                            $("#thirdSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                        });

                        form.val("categoryForm",m.product)
                        $("#demo1").attr("src",m.product.homeImg);
                        renderUpload();
                    })
            } else if (obj.event === 'delete') {
                    console.log("111")
                layer.confirm("您确定要删除该商品吗？",function () {
                    $.post("/product/delete",{id:data.id},function () {
                        $("#searchBtn").click();
                        layer.closeAll();
                    });
                });
            }else if (obj.event === 'uppers'){
                $.get("/attachment/attsProduct?pid="+obj.data.id,function (atts) {
                    for (var i = 0; i < atts.length; i++) {
                        var att = atts[i];
                        var img = $("<img/>", {
                            src: att.url,
                            id: att.id
                        });
                        $("#preview").append(img);
                    }
                    layer.open({
                        type:1,
                        area:["600px","500px"],
                        title:"上传多附件",
                        content:$("#uppersTemplate").html()
                    });
                    $.each(atts, function(i, v) {
                        var imgWrapper = $('<div/>', {
                            css: {
                                position: 'relative',
                                display: 'inline-block'
                            },
                        });

                        var img = $('<img/>', {
                            style: "margin: 5px 5px 5px 5px",
                            src: v.path,
                            class: "layui-upload-img",
                        });

                        var icon = $('<i class="layui-icon layui-icon-delete" style="color: #fff; font-size: 18px; position: absolute; top: 2px; right: 2px;"></i>');

                        imgWrapper.hover(
                            function() {
                                // 鼠标经过时添加遮罩
                                $(this).append($('<div/>', {
                                    css: {
                                        position: 'absolute',
                                        top: 0,
                                        left: 0,
                                        width: '100%',
                                        height: '100%',
                                        backgroundColor: 'rgba(0, 0, 0, 0.2)',
                                        textAlign: 'center'
                                    },
                                    html: icon
                                }));
                            },
                            function() {
                                // 鼠标移出时移除遮罩
                                $(this).find('div').remove();
                            }
                        ).click(function() {
                            layer.confirm("确定要删除这张图片吗？", function(index) {
                                layer.close(index);
                                $.post("/attachment/delete", {id: v.id}, function(res) {
                                    if (res.code === 0) {
                                        imgWrapper.remove();
                                    } else {
                                        layer.msg(res.msg, {icon: 2});
                                    }
                                });
                            });
                        });

                        imgWrapper.append(img);

                        $('#demo2').append(imgWrapper);
                    });


                    var ids="";
                    upload.render({
                        elem: '#test2',
                        url: '/attachment/upload',
                        multiple: true,
                        before: function(obj){
                            obj.preview(function(index, file, result){
                                var img = $('<img width="80px" height="80px" style="margin: 5px 5px 5px 5px" src="'+ result +'" alt="'+ file.path +'" class="uploaded-img"/>').attr('data-index', index);
                                $('#demo2').append(img);
                            });
                        },
                        done:function(res, index, upload){
                            if(res.code === 0){
                                var imageId = res.data.id;     // 获取上传成功后服务器返回的文件id
                                if (ids!==""){
                                    ids+=",";
                                }
                                ids+=res.data.id;// 将新文件id拼接到现有字符串中，用逗号分隔
                                $('.uploaded-img[data-index='+index+']').attr('data-id', imageId).on('click', function(){
                                    var delthis = $(this);
                                    layer.confirm('确定要删除吗？', function(index){
                                        var imageId = delthis.attr('data-id');      // 获取当前图片的文件id，注意这里使用了data-id属性存储文件id
                                        $.post("/attachment/delete", {id: imageId}, function(res){
                                            if(res.code === 0){
                                                delthis.remove();
                                                ids = ids.replace(',' + imageId, '');     // 从字符串中移除相应的文件id，用逗号分隔
                                                layer.close(index);
                                            }else{
                                                layer.msg(res.msg, {icon: 2});
                                            }
                                        });
                                    });
                                });
                            }
                        },
                        allDone:function(res){     // 提交所有上传成功的文件id
                            console.log(ids);
                            console.log("888"+obj.data.id)
                            $.post("/attachment/attProduct", {ids: ids, pid: obj.data.id});
                        }
                    });
                } )
            }
        });

        var loadSubCategory = function (fn){
            $.get("/category/child",{id:$("#firstSelect").val()},function(categories) {
                $("#secondSelect").html("");
                $.each(categories,function (i,v) {
                    $("#secondSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                });
                form.render();
                if (fn!=null) {
                    fn();
                }

            });
        };
        var loadSubCategory01 = function (fn){
            $.get("/category/child",{id:$("#secondSelect").val()},function(categories) {
                $("#thirdSelect").html("");
                $.each(categories,function (i,v) {
                    $("#thirdSelect").append('<option value="'+v.id+'">'+v.name+'</option>')
                });
                form.render();
                if (fn!=null) {
                    fn();
                }
            });
        };
        form.on("select(topCategory)",function() {
            loadSubCategory();
        });
        form.on("select(lastCategory)",function() {
            loadSubCategory01();
        });
    });
</script>
</body>
</html>